package tech.yunland.shop.domain.dao;

import com.moyuer.bsf.domain.dao.BaseDao;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import tech.yunland.shop.domain.model.Goods;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author: 袁首京<yuanshoujing@gmail.com> 16/3/29
 */
@Repository
public class GoodsDao extends BaseDao<Goods, String> {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	public Goods getGoodsName(String name, String organId) {
		Goods result = null;
		DetachedCriteria criteria = DetachedCriteria.forClass(Goods.class);
		if (organId != null) {
			criteria.createCriteria("organ").add(Restrictions.idEq(organId));
		}
		if (name != null) {
			criteria.add(Restrictions.eq("name", name));
		}
		List<Goods> goods = this.findByCriteria(criteria);

		if (goods.size() == 0) {
			return result;
		}
		result = goods.get(0);

		return result;
	}

	public Goods getGoodsCode(String code, String organId) {
		Goods result = null;
		DetachedCriteria criteria = DetachedCriteria.forClass(Goods.class);
		if (organId != null) {
			criteria.createCriteria("organ").add(Restrictions.idEq(organId));
		}
		if (code != null) {
			criteria.add(Restrictions.eq("code", code));
		}
		List<Goods> goods = this.findByCriteria(criteria);

		if (goods.size() == 0) {
			return result;
		}
		result = goods.get(0);

		return result;
	}
	
	/**
	 * 查询规定店铺下商品的会员平均价格
	 * 
	 * @param organId
	 * @param goodsId
	 * @return
	 */
	public List<Map<String, Object>> getMemberPrize(String organId,String goodsId){
		
		String sql=" select  prize.goods_id,round(prize,2) as member_prize from" +
				" (select goods_id,sum(amount)/sum(quantity) as prize from goods_paid " +
				" where organ_id='"+organId+"' and goods_id='"+goodsId+"' and quantity<> 0 and amount <> 0" +
				" group by goods_id) prize ";
		
		return jdbcTemplate.queryForList(sql);
				
	}
	
}
















